// _form/element/checbox-group/index.js
const { c0, $fn, $config } = getApp()
Component({
    behaviors: ['wx://form-field-group'],
    options:{
        virtualHost: true
    },
    properties: {
        data: null,
        name: String,
        value: null,
        api: null,
        param: null,
        idStr: null,
        nameStr: null,
        disabled: Boolean,
        color: null,
        count: null,
        width: null,
        gapX: null,
        gapY: null,
        fontSize:Number,
        str:Boolean
    },
    data: {
        c0,
        $config
    },
    lifetimes:{
        attached(){
            let { api, data, value } = this.data
            if(api){
                $http.pull(null, api, { param }).then(data=>{
                    this.setValue( data, value )
                })
            }else{
                this.setValue( data, value )
            }
        }
    },
    methods: {
        change({ detail: { value } }){
            this.setData({ value })
            this.triggerEvent('change', value)
        },
        setValue(data, value){
            if($fn.hasArray( value )){
                let { idStr } = this.data
                idStr = idStr || $config.idStr
                const stack = []
                data.forEach( v =>{
                    v.checked = false
                    value.forEach((p,k)=>{
                        if(v[idStr] === p){
                            stack.push( v )
                        }
                    })
                })
                stack.forEach( v => v.checked = true )
                this.setData({ data })
            }
        },
    },
    observers:{
        'value': function(value){
            if(value){
                setTimeout(()=>{
                    this.setValue( this.data.data, value )
                })
            }
        }
    }
})
